package com.atguigu.seckill.scheduleTask;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.seckill.feign.CouponFeignService;
import com.atguigu.seckill.service.SecKillSevice;
import com.atguigu.seckill.to.seckillSessionTo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SeckillScheduled {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SecKillSevice secKillSevice;

    @Autowired
    RedissonClient redissonClient;


    /**
     * 每天凌晨三点去扫描最近三天要上架的商品
     */
    @Scheduled(cron = "* * 1 * * ?")
    public void upProductsOf3Days() {
        log.info("秒杀商品上架功能开启");
        String secKillRedissonKey = "secKill";
        RLock lock = redissonClient.getLock(secKillRedissonKey);
        //上锁
        lock.lock(10, TimeUnit.SECONDS);
        try {
            R res = couponFeignService.getSecKillOf3Days();
            if (res.getCode() == 0) {
                //远程调用响应成功
                List<seckillSessionTo> sessionToList = res.getData(new TypeReference<List<seckillSessionTo>>() {
                });

                //redis中存储活动的相关信息
                secKillSevice.saveSecKillAc(sessionToList);

                //redis中存储商品的详情信息
                secKillSevice.saveSecKillProd(sessionToList);
            }
        } finally {
            //解锁
            lock.unlock();
        }
        log.info("秒杀商品上架功能结束");
    }


}
